package me.shurufa.fragments;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.malinskiy.superrecyclerview.SuperRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.okhttpfinal.HttpRequest;
import de.greenrobot.event.EventBus;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import me.shurufa.R;
import me.shurufa.activities.ModifyBookCommentActivity;
import me.shurufa.activities.NewDigestActivity;
import me.shurufa.activities.NewLoginActivity;
import me.shurufa.adapter.BookCommentNewAdapter;
import me.shurufa.adapter.BookCommentNewMeAdapter;
import me.shurufa.bean.BookComment;
import me.shurufa.controller.BookCommentCommentCounterController;
import me.shurufa.controller.DataController;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.model.BookListResponse;
import me.shurufa.net.API;
import me.shurufa.net.BaseResponse;
import me.shurufa.net.RequestParams;
import me.shurufa.net.RequestServerTask;
import me.shurufa.net.okhttp.callback.HttpCallback;
import me.shurufa.response.BookCommentListResp;
import me.shurufa.response.CreateBookCommentResp;
import me.shurufa.response.base.BaseResp;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Global;
import me.shurufa.utils.HttpUtil;
import me.shurufa.utils.LogUtils;
import me.shurufa.utils.NetworkUtils;
import me.shurufa.utils.RecyclerViewStateUtils;
import me.shurufa.utils.Utils;
import me.shurufa.widget.LoadingFooter;
import me.shurufa.widget.pulltorefresh.SrfPtrFrameLayout;
import me.shurufa.widget.recyclerview.EndlessRecyclerOnScrollListener;
import me.shurufa.widget.recyclerview.HeaderAndFooterRecyclerViewAdapter;
import me.shurufa.widget.simpledialog.SimpleDialog;
import me.shurufa.widget.timelineheader.HeaderCommentBarLayout;

/**
 * 作者 : andy
 * 日期 : 16/3/9 10:31
 * 邮箱 : andyxialm@gmail.com
 * 描述 : 书评Fragment
 */
public class MyBookCommentFragment extends BaseFragment implements View.OnClickListener, AppBarLayout.OnOffsetChangedListener {

    @Bind(R.id.recycler_view)
    SuperRecyclerView recyclerView;

    @Bind(R.id.ptr_refresh)
    SrfPtrFrameLayout ptrRefresh;

    @Bind(R.id.header_comment_bar)
    HeaderCommentBarLayout header_comment_bar;

    @Bind(R.id.appbar)
    AppBarLayout mAppBar;

    @Bind(R.id.iv_empty)
    ImageView iv_empty;

    private ArrayList<BookComment> mDataList;
    private BookCommentNewAdapter mCommentAdapter;
    private BookCommentNewMeAdapter mCommentMeAdapter;
    private HeaderAndFooterRecyclerViewAdapter mHeaderAndFooterRecyclerViewAdapter;
    private int mVerticalOffset;
    private int mWhereFrom;
    private long bookId;
    private String mBookname;
    private String mUserId;
    private Handler mHandler = new Handler();

    // 刷新需要
    private int mPage;
    private boolean hasMore = true;
    private View.OnClickListener mFooterClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (NetworkUtils.isNetAvailable(getActivity())) {
                RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                loadData(mPage);
            }
        }
    };

    public static MyBookCommentFragment newInstance(long bookId, String bookname, int whereFrom, String userId) {
        MyBookCommentFragment fragment = new MyBookCommentFragment();
        Bundle args = new Bundle();
        args.putLong(Constants.ARG_BOOK_ID, bookId);
        args.putInt(Constants.ARG_FROM_WHERE, whereFrom);
        args.putString(Constants.ARG_BOOK_TITLE, bookname);
        args.putString(Constants.ARG_USER_ID, userId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            bookId = getArguments().getLong(Constants.ARG_BOOK_ID);
            mWhereFrom = getArguments().getInt(Constants.ARG_FROM_WHERE);
            mBookname = getArguments().getString(Constants.ARG_BOOK_TITLE);
            mUserId = getArguments().getString(Constants.ARG_USER_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_comment_list_new, container, false);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 400);
    }

    @Override
    protected void initUI(View view) {
        super.initUI(view);
        // 初始化刷新
        setRefresh();
        mDataList = new ArrayList<>();

        mCommentAdapter = new BookCommentNewAdapter(getActivity(), mBookname, mDataList, mWhereFrom);
        mCommentMeAdapter = new BookCommentNewMeAdapter(getActivity(), mBookname, mDataList, mWhereFrom);
        mHeaderAndFooterRecyclerViewAdapter = new HeaderAndFooterRecyclerViewAdapter(mCommentMeAdapter);
        recyclerView.setAdapter(mHeaderAndFooterRecyclerViewAdapter);
        recyclerView.getRecyclerView().setOverScrollMode(View.OVER_SCROLL_NEVER);

        // 默认隐藏，刷新后无数据的话才显示
        recyclerView.getEmptyView().setVisibility(View.GONE);

        //setLayoutManager
        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(manager);
        recyclerView.setOnScrollListener(mOnScrollListener);

        initListener();

        if (Constants.FROM_USER_CENTER == mWhereFrom) {
            header_comment_bar.hideMe();
        }

        // 从消息列表跳进来的， 隐藏顶部选择条
        if (Constants.TYPE_FROM_NOTICE_MESSAGE_BOOKCOMMENT == mWhereFrom) {
            header_comment_bar.setVisibility(View.GONE);
        }

        if (mWhereFrom == Constants.TYPE_FRAGMENT_MYCOLLECT) {
            header_comment_bar.setVisibility(View.GONE);
        }

        if (mWhereFrom == Constants.TYPE_FRAGMENT_MYCOMMENT) {
            header_comment_bar.setVisibility(View.GONE);
        }

    }

    private EndlessRecyclerOnScrollListener mOnScrollListener = new EndlessRecyclerOnScrollListener() {

        @Override
        public void onLoadNextPage(View view) {
            super.onLoadNextPage(view);
            try {
                LoadingFooter.State state = RecyclerViewStateUtils.getFooterViewState(recyclerView.getRecyclerView());
                if (state == LoadingFooter.State.Loading) {
                    LogUtils.kLog().e("the state is Loading, just wait..");
                    return;
                }

                if (hasMore) {
                    if (!NetworkUtils.isNetAvailable(getActivity())) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                        return;
                    }
                    // loading more
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.Loading, null);
                    loadData(mPage);
                } else {
                    //the end
                    RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.TheEnd, null);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
    };

    private void setRefresh() {
        ptrRefresh.setResistance(2.0F);
        ptrRefresh.setRatioOfHeaderHeightToRefresh(1.0F);
        ptrRefresh.setDurationToClose(300);
        ptrRefresh.setDurationToCloseHeader(1000);
        ptrRefresh.setLoadingMinTime(500);
        ptrRefresh.setPullToRefresh(false);
        ptrRefresh.setKeepHeaderWhenRefresh(true);
        ptrRefresh.disableWhenHorizontalMove(true);
        ptrRefresh.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
                return mVerticalOffset == 0 && PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, ((SuperRecyclerView) view).getRecyclerView(), view1);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                refresh();
            }
        });
    }

//Load and Refresh


    @Override
    public void refresh() {
        super.refresh();
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ptrRefresh != null && ptrRefresh.isRefreshing()) {
                    ptrRefresh.refreshComplete();
                }
            }
        }, 2000);
        onRefresh();
    }

    public void onRefresh() {
        mPage = 1;
        loadData(mPage);
    }

    private void onRefresh(boolean isChangedTab) {
        if (isChangedTab) {
            mCommentAdapter.clear();
        }
        //        自动刷新一次
        ptrRefresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                ptrRefresh.autoRefresh(true);
            }
        }, 50);
    }

    protected void loadData(final int page) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("page", page);
        params.addFormDataPart("book_id", bookId);
        params.addFormDataPart("order_by", "time_down");
        params.addFormDataPart("user_id", PersistenceUtils.getUserId());

        HttpRequest.post(API.GET_COMMENT_LIST_BY_BOOKID_USERID, params, new HttpCallback<BookCommentListResp>() {

            @Override
            public void onRespSuccess(final BookCommentListResp resp) {
                try {
                    handleResponse(resp, (page == 0 || page == 1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BookCommentListResp resp) {

            }

            @Override
            public void onStart() {
                super.onStart();
                if (NetworkUtils.isNetAvailable(getActivity())) {
                    RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), LoadingFooter.State.Loading);
                } else {
                    // 是上拉加载
                    if (mPage > 1) {
                        RecyclerViewStateUtils.setFooterViewState(getActivity(), recyclerView.getRecyclerView(), Constants.PAGE_REQUEST_COUNT, LoadingFooter.State.NetWorkError, mFooterClick);
                    }
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                refreshComplete();
            }
        });
    }

    /**
     * Require run in UIThread
     */
    public void refreshComplete() {
        // 是上拉加载更多
        if (mPage > 1) {
            RecyclerViewStateUtils.setFooterViewState(recyclerView.getRecyclerView(), hasMore ? LoadingFooter.State.Normal : LoadingFooter.State.TheEnd);
        }

        // 是下拉加载
        if (ptrRefresh != null && mPage <= 1) {
            ptrRefresh.refreshComplete();
        }
    }

    /**
     * 处理返回结果
     * 1. 去重
     *
     * @param listResp        mDataList
     * @param isPullToRefresh boolean
     */
    private void handleResponse(BookCommentListResp listResp, boolean isPullToRefresh) {
        // 是否还有更多
        hasMore = mPage < listResp.max_page;

        // 1. 判空
        if (listResp.data == null || Utils.isNullForList(listResp.data)) {
            if (isPullToRefresh) {
                recyclerView.getEmptyView().setVisibility(View.VISIBLE);
            }
            return;
        }

        // 2. 去重
        if (!isPullToRefresh) {
            listResp.data = DataController.getValidBookCommentList(mDataList, listResp.data);
        } else {
            mCommentMeAdapter.clear();
            mCommentMeAdapter.notifyDataSetChanged();
        }

        // 3. 添加进列表并刷新
        mCommentMeAdapter.append(listResp.data);
        mCommentMeAdapter.notifyDataSetChanged();

        // 4. 页码自增
        mPage++;
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.book_img:
                Utils.showToast(R.string.my_favourite_digest);
                break;
            case R.id.left_text:
                intent = new Intent(getActivity(), NewDigestActivity.class);
                startActivity(intent);
                break;
            case R.id.right_text:
                intent = new Intent(Constants.ACTION_MAIN_SWITCH);
                intent.putExtra(Constants.EXTRA_SWITCH_INDEX, 0);
                EventBus.getDefault().post(intent);
                break;
        }
    }

    @Override
    public void onEventMainThread(Intent intent) {
        super.onEventMainThread(intent);
        if (Constants.ACTION_SHELVES_FAVOURITE.equals(intent.getAction())) {
        } else if (Constants.ACTION_BOOKSHELVES_REFRESH.equals(intent.getAction())
                || Constants.ACTION_ADD_DIGEST_COMPLETE.equals(intent.getAction())) {
            refresh();
        }

        // 发送书评后插入书评数据
        if (Constants.EVENT_SEND_BOOK_COMMENT.equals(intent.getAction())) {
            BookComment bookComment = (BookComment) intent.getSerializableExtra(Constants.EVENT_SEND_BOOK_COMMENT);
            if (mDataList == null) {
                mDataList = new ArrayList<>();
            }
            mDataList.add(0, bookComment);
            mCommentMeAdapter.notifyItemInserted(0);
            return;
        }

        // 修改书评
        if (Constants.EVENT_MODIFY_BOOK_COMMENT.equals(intent.getAction())) {
            int position = intent.getIntExtra(Constants.ARG_MODIFY_POSITION, -1);
            String content = intent.getStringExtra(Constants.ARG_COMMENT_CONTENT);
            if (position < 0) {
                return;
            }
            BookComment bookComment = mDataList.get(position);
            bookComment.content = content;
            mCommentMeAdapter.notifyItemChanged(position);
        }

        // 添加了评论
        if (Constants.EVENT_SEND_COMMENT.equals(intent.getAction())) {
            int type = intent.getIntExtra(Constants.ARG_PARENT_TYPE, 0);
            if (Constants.TYPE_COMMENT_BOOK_COMMENT == type) {
                int bookCommentId = intent.getIntExtra(Constants.ARG_PARENT_ID, 0);
                BookCommentCommentCounterController controller = new BookCommentCommentCounterController(mCommentAdapter, mDataList, bookCommentId);
                controller.handleAddCounter();
            }
        }

    }

    private void initListener() {
        mAppBar.addOnOffsetChangedListener(this);
        recyclerView.setOnScrollListener(mOnScrollListener);

        // 评论点击按钮监听
        mCommentAdapter.setOnSocialBarClickListener(new BookCommentNewAdapter.OnSocialBarClickListener() {

            @Override
            public void onPraiseClick(boolean prePraise, BookComment comment) {
                if (!prePraise) {
                    reqPraise(comment);
                } else {
                    reqCancelPraise(comment);
                }
            }

            @Override
            public void onCollectClick(boolean preCollect, BookComment comment) {
                if (!preCollect) {
                    reqCollect(comment);
                } else {
                    reqCancelCollect(comment);
                }
            }
        });

        mCommentMeAdapter.setOnSocialBarClickListener(new BookCommentNewMeAdapter.OnSocialBarClickListener() {
            @Override
            public void onPraiseClick(boolean prePraise, BookComment comment) {
                if (!prePraise) {
                    reqPraise(comment);
                } else {
                    reqCancelPraise(comment);
                }
            }

            @Override
            public void onDelClick(int position, BookComment comment) {
                showDelDlg(position, comment);
            }

            @Override
            public void onEditClick(int position, BookComment bookComment) {
                Intent in = new Intent(getActivity(), ModifyBookCommentActivity.class);
                ModifyBookCommentActivity.initArguments(in, position, "" + bookComment.id, bookComment.content);
                startActivity(in);
            }
        });
    }

    /**
     * 收藏
     *
     * @param comment
     */
    private void reqCollect(final BookComment comment) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", comment.id);
        params.addFormDataPart("item", "comment");

        HttpRequest.post(API.ADD_FAV, params, new HttpCallback<BaseResp>(getActivity()) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    comment.is_fav = 1;
                    mCommentAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    /**
     * 取消点赞
     *
     * @param comment
     */
    private void reqCancelPraise(final BookComment comment) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", comment.id);
        params.addFormDataPart("item", "comment");

        HttpRequest.post(API.DEL_ZAN, params, new HttpCallback<BaseResp>(getActivity()) {
            @Override
            public void onRespSuccess(BaseResp resp) {
                try {
                    comment.is_zan = 0;
                    comment.zan_num -= 1;
                    if (comment.zan_num < 0) {
                        comment.zan_num = 0;
                    }
                    mCommentMeAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }
        });
    }

    /**
     * 点赞
     *
     * @param comment
     */
    private void reqPraise(final BookComment comment) {

        RequestParams params = new RequestParams();
        params.addFormDataPart("id", comment.id);
        params.addFormDataPart("item", "comment");

        HttpRequest.post(API.ADD_ZAN, params, new HttpCallback<BaseResp>(getActivity()) {
            @Override
            public void onRespSuccess(BaseResp resp) {
                try {
                    comment.is_zan = 1;
                    comment.zan_num += 1;
                    mCommentMeAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp resp) {

            }
        });

    }

    /**
     * 取消点赞
     *
     * @param comment
     */
    private void reqCancelCollect(final BookComment comment) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", comment.id);
        params.addFormDataPart("item", "comment");

        HttpRequest.post(API.ADD_FAV, params, new HttpCallback<BaseResp>(getActivity()) {

            @Override
            public void onRespSuccess(BaseResp baseResp) {
                try {
                    comment.is_fav = 0;
                    mCommentAdapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(BaseResp baseResp) {

            }
        });
    }

    /**
     * 删除书评
     *
     * @param bookComment
     */
    private void showDelDlg(final int position, final BookComment bookComment) {
        SimpleDialog dialog = new SimpleDialog(getActivity());
        dialog.setAnimationEnable(true);
        dialog.setTitle("删除书评");
        dialog.setContentText("确认删除此条书评?");
        dialog.setOnPositiveListener(getString(R.string.ok), new SimpleDialog.OnPositiveListener() {
            @Override
            public void onClick(SimpleDialog dialog) {
                dialog.dismiss();
                reqDelBookComment(position, bookComment);
            }
        })
                .setOnNegativeListener(getString(R.string.cancel), new SimpleDialog.OnNegativeListener() {
                    @Override
                    public void onClick(SimpleDialog dialog) {
                        dialog.dismiss();
                    }
                }).show();
    }

    /**
     * 请求删除书评
     *
     * @param position    位置
     * @param bookComment 书评
     */
    private void reqDelBookComment(final int position, BookComment bookComment) {
        RequestParams params = new RequestParams();
        params.addFormDataPart("id", bookComment.id);

        HttpRequest.post(API.DEL_BOOK_COMMENT, params, new HttpCallback<CreateBookCommentResp>(getActivity()) {
            @Override
            public void onRespSuccess(CreateBookCommentResp resp) {
                try {
                    Utils.showToast(getString(R.string.delete_success));
                    Intent in = new Intent(Constants.EVENT_DEL_BOOK_COMMENT);
                    in.putExtra(Constants.ARG_BOOK_ID, (int) bookId);
                    EventBus.getDefault().post(in);
                    mDataList.remove(position);
                    mCommentMeAdapter.notifyItemRemoved(position);
                    mCommentMeAdapter.notifyItemRangeChanged(position, 1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onRespFailure(CreateBookCommentResp resp) {

            }

        });
    }

    @Override
    public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
        mVerticalOffset = verticalOffset;
    }

    public RecyclerView findRecyclerView() {
        if (recyclerView != null) {
            return recyclerView.getRecyclerView();
        }
        return null;
    }
}
